from rest_framework.generics import GenericAPIView
from meiduo_admin.serializer.option_serializer import *
from meiduo_admin.pages import MyPage
from goods.models import *
from rest_framework.response import Response


# 请求方式： GET /meiduo_admin/specs/options/
class OptionsView(GenericAPIView):
    serializer_class = OptionSerialzier
    pagination_class = MyPage
    queryset = SpecificationOption.objects.all()

    def get(self, request):
        """查询所有规格"""
        options = self.get_queryset()
        page = self.paginate_queryset(options)
        if page:
            page_serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(page_serializer.data)
        serializer = OptionSerialzier(options, many=True)
        return Response(serializer.data)

    def post(self, request):
        """添加规格"""
        option = self.request.data
        print(option)
        serializer = self.get_serializer(data=option)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=201)


# 请求方式： GET /meiduo_admin/goods/specs/simple/
class OptionSimple(GenericAPIView):
    serializer_class = OptionSpecificationSerializer
    queryset = SPUSpecification.objects.all()

    def get(self, request):
        """获取规格"""
        options = self.get_queryset()
        serializer = self.get_serializer(options, many=True)
        return Response(serializer.data)


# 请求方式： GET /meiduo_admin/specs/options/(?P<pk>\d+)/
class OptionsOnlyView(GenericAPIView):
    serializer_class = OptionSerialzier
    queryset = SpecificationOption.objects.all()

    def get(self, request, pk):
        """查询单一数据规格"""
        option_only = SpecificationOption.objects.get(pk=pk)
        serializer = OptionSerialzier(option_only)
        return Response(serializer.data)

    # 请求方式：PUT/meiduo_admin/specs/options/(?P<pk>\d+)/
    def put(self, request, pk):
        option_obj = self.get_object()
        print(option_obj)
        serializer = OptionSerialzier(instance=option_obj, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def delete(self, request, pk):
        option_obj = self.get_object()
        option_obj.delete()
        return Response({})